package club.samubird.simpledatahandlekit.robotmessage;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sam
 * @date 2019/8/2 11:24
 * @description 企业微信消息通知
 */
@Slf4j
@Component
public class WorkWxNotifyUtil {

	@Value("${robot.tag.noticeUrl}")
	private String url;

	@Value("${robot.tag.isNotifyAll}")
	private Boolean isNotifyAll;

	@Value("#{'${robot.tag.mentionedMobileList}'.split(',')}")
	private List<String> mentionedMobileList;

	public void sendNotify(String content) {
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(this.url).openConnection();
			// 设置可输入
			connection.setDoInput(true);
			// 设置该连接是可以输出的
			connection.setDoOutput(true);
			// 设置请求方式
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, Object> data = new HashMap<>(8);
			data.put("msgtype", "text");
			Map<String, Object> innerData = new HashMap<>(8);
			innerData.put("content", content);
			if (this.isNotifyAll) {
				this.mentionedMobileList.add("@all");
			}
			if (!this.mentionedMobileList.isEmpty()) {
				innerData.put("mentioned_mobile_list", this.mentionedMobileList);
			}
			data.put("text", innerData);
			PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
			pw.write(objectMapper.writeValueAsString(data));
			pw.flush();
			pw.close();
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			String line = null;
			StringBuilder result = new StringBuilder();
			result.append("企业微信消息通知： ").append(content).append("发送的结果是: ");
			// 读取数据
			while ((line = br.readLine()) != null) {
				result.append(line + "\n");
			}
			connection.disconnect();
			log.info(result.toString());
		} catch (Exception e) {
			log.error("企业微信消息通知出现异常", e);
		}
	}


}
